package cn.net.xyan.pay.core.utils

import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import javax.servlet.http.HttpServletRequest

/**
 * Created by zarra on 16/6/8.
 */
object RequestUtils {


    fun httpServletRequest(): HttpServletRequest? {
        try {
            val curRequest = (RequestContextHolder.currentRequestAttributes() as ServletRequestAttributes)
                    .request
            return curRequest
        } catch (e: Throwable) {
            return null
        }

    }

    fun remoteAddr(): String {
        return httpServletRequest()!!.remoteAddr
    }

    fun absolutePath(path: String): String {
        return contextPath() + path
    }

    fun absoluteURL(path: String): String {
        return appRootURL() + path
    }

    fun contextPath(): String {
        val request = httpServletRequest()
        var contextPath = request!!.contextPath
        if ("/" == contextPath) {
            contextPath = ""
        }
        return contextPath
    }

    fun appRootURL(): String {
        val request = httpServletRequest()
        val scheme = request!!.scheme
        val host = request.serverName
        val port = request.serverPort
        var needPort = true
        if ("http" == scheme && port == 80 || "https" == scheme && port == 443) {
            needPort = false
        }

        var sPort = String.format(":%d", port)
        if (needPort == false)
            sPort = ""

        return String.format("%s://%s%s%s", scheme, host, sPort, contextPath())
    }
}
